﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace TLSharp
{
    public class TeamNote
    {
        public int NoteID;
        public int TeamID;
        public bool bPrivate;
        public string Note;
        public DateTime  DateAdded;
        public int ReplyToNoteID = -1;

        public List<float> PrivateNoteOwners;
        public List<string> Replies;

        private List<TeamNote> _Replies = null;

        public List<TeamNote> RepliesObjects
        {
            get
            {
                if (_Replies == null && Replies != null)
                {
                    _Replies = new List<TeamNote>();
                    foreach (string ThisString in Replies)
                    {
                        Newtonsoft.Json.Linq.JObject o = JObject.Parse(ThisString);

                        TeamNote b = (TeamNote)(new JsonSerializer()).Deserialize(new JsonTokenReader(o), typeof(TeamNote));

                        JValue ThisValue = new JValue(ThisString);
                        _Replies.Add(b);
                    }
                }
                else if (Replies == null)
                {
                    _Replies = new List<TeamNote>();

                }
                return _Replies;
            }
        }

        public List<TeamNote> _Flat;
        public List<TeamNote> Flat
        {
            get
            {
                if (_Flat != null)
                { }
                else
                {
                    List<TeamNote> ThisList = new List<TeamNote>() { this };
                    ThisList.AddRange(this.RepliesObjects.SelectMany(p => p.Flat));
                    _Flat = ThisList.OrderByDescending(p=>p.DateAdded).ToList();
                }
                return _Flat;
            }
        }

        private DateTime _MostRecentAdded;
        public DateTime MostRecentAdded
        {
            
            get
            {
                if(_MostRecentAdded==null)
                {}
                else
                {
                    DateTime MaxTime = DateAdded;
                    foreach (TeamNote ThisNote in RepliesObjects)
                    {
                        if (ThisNote.MostRecentAdded > MaxTime)
                        {
                            MaxTime = ThisNote.MostRecentAdded;
                        }
                    }
                    _MostRecentAdded = MaxTime;
                  }
                return _MostRecentAdded;
            }
        }


    }
}
